#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QHBoxLayout>
#include <QTableWidget>
#include <QSplitter>

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	// init video player & table view
	videoPlayer = new Phonon::VideoPlayer();
	videoPlayer->setMinimumSize(320, 200);
	videoPlayer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
	tableWidget = new QTableWidget(1, 1);
	tableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
	splitterWidget = new QSplitter;
	splitterWidget->addWidget(videoPlayer);
	splitterWidget->addWidget(tableWidget);
	splitterWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
	ui->videoVLayout->insertWidget(0, splitterWidget);
	// init sliders
	seekSlider = new Phonon::SeekSlider();
	seekSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	seekSlider->setMinimumHeight(20);
	volumeSlider = new Phonon::VolumeSlider();
	volumeSlider->setMinimumSize(100, 20);
	volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	QHBoxLayout *slidersLayout = new QHBoxLayout();
	slidersLayout->addWidget(seekSlider);
	slidersLayout->addWidget(volumeSlider);
	ui->videoVLayout->insertLayout(1, slidersLayout);
}

MainWindow::~MainWindow()
{
	delete ui;
	delete videoPlayer;
	delete seekSlider;
}

//---------------------------Slots-----------------------------------

void MainWindow::openFile()
{
	QString fileName = QFileDialog::getOpenFileName(this);
	Phonon::MediaSource src(fileName);
	if (src.type() == Phonon::MediaSource::Invalid) {
		QMessageBox::critical(this, tr("Bad source"), tr("Can't open file: Unknown type"));
	} else {
		videoPlayer->load(src);
		ui->playButton->setEnabled(true);
		ui->stopButton->setEnabled(true);
		videoPlayer->stop();
		// Binding sliders
		seekSlider->setMediaObject(videoPlayer->mediaObject());
		volumeSlider->setAudioOutput(videoPlayer->audioOutput());
	}
}

void MainWindow::stop()
{
	videoPlayer->stop();
	ui->playButton->setText(tr("Play"));
}

void MainWindow::play(bool playFlag)
{
	if (!videoPlayer->mediaObject()->isValid()) return;
	if (playFlag) {
		videoPlayer->play();
		ui->playButton->setText(tr("Pause"));
	} else {
		videoPlayer->pause();
		ui->playButton->setText(tr("Play"));
	}
}
